import React, { useState } from 'react';

// TypeScript 类型定义
type FixItem = {
  original: string;
  suggestion: string[];
  adopt_suggestions: string;
};

const AuditFixSuggestions: React.FC<{
    suggestions: FixItem[];
    onSubmit: (data: FixItem[], storageKey: string) => void;
    storageKey: string; 
  }> = ({ suggestions, onSubmit, storageKey }) => {

  const [editedSuggestions, setEditedSuggestions] =
    useState<FixItem[]>(suggestions);



  const adoptSuggestion = (index: number, suggestion: string) => {
    const updatedSuggestions = editedSuggestions.map((item, i) => {
      if (i === index) {
        return { ...item, adopt_suggestions: suggestion };
      }
      return item;
    });
    setEditedSuggestions(updatedSuggestions);
  };

  const handleEditAdoptedSuggestion = (index: number, value: string) => {
    const updatedSuggestions = [...editedSuggestions];
    updatedSuggestions[index].adopt_suggestions = value;
    setEditedSuggestions(updatedSuggestions);
  };

  // 高亮处理函数
  const parseHighlight = (text: string) => {
    const regex =
      /<ais-highlight-0000000000>(.*?)<\/ais-highlight-0000000000>/g;
    const parts = text.split(regex);

    return parts.map((part, index) =>
      index % 2 === 1 ? (
        <span key={index} className="bg-red-200">
          {part}
        </span>
      ) : (
        part
      ),
    );
  };

  return (
    <div className="mx-auto max-w-4xl">
      { (editedSuggestions || []).map((suggestion, index) => (
        <div key={index} className="my-4 rounded-lg bg-white p-4 shadow-md">
          <p className="mb-2 text-lg font-semibold text-gray-800">原文:</p>
          <p>{parseHighlight(suggestion.original)}</p>
          <div className="mt-2">
            {suggestion.suggestion.map((sug, sugIndex) => (
              <p
                key={sugIndex}
                className={`p-2 ${
                  suggestion.adopt_suggestions === sug
                    ? 'bg-green-500 text-white'
                    : 'hover:bg-gray-200'
                } cursor-pointer`}
                onClick={() => adoptSuggestion(index, sug)}
              >
                {sug}
              </p>
            ))}
          </div>
          {suggestion.adopt_suggestions && (
            <textarea
              className="mt-2 h-24 w-full rounded-md border-2 border-gray-200 p-2 focus:border-blue-500 focus:ring focus:ring-blue-500 focus:ring-opacity-50"
              value={suggestion.adopt_suggestions}
              onChange={(e) =>
                handleEditAdoptedSuggestion(index, e.target.value)
              }
            />
          )}
        </div>
      ))}
      <button
        className="mt-4 rounded-lg bg-blue-500 px-4 py-2 text-white transition-colors hover:bg-blue-700"
        onClick={() => onSubmit(editedSuggestions,storageKey)}
      >
        提交建议
      </button>
    </div>
  );
};

export default AuditFixSuggestions;
